<?php
// 显示所有错误
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// 引入必要的文件
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../../config/database.php';

// 初始化会话
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// 检查登录状态（除了登录页面外的所有页面）
$current_page = basename($_SERVER['PHP_SELF']);
$isLoggedInDb = isset($_SESSION['admin_user_id']);
$isLoggedInSimple = isset($_SESSION['admin_logged_in']) && $_SESSION['admin_logged_in'] === true;
$isLoggedIn = $isLoggedInDb || $isLoggedInSimple;

if ($current_page != 'login.php' && $current_page != 'fixed_login.php' && !$isLoggedIn) {
    header('Location: login.php');
    exit;
}

// 如果只有简单登录，但没有用户ID，则设置一个临时ID
if ($isLoggedInSimple && !$isLoggedInDb && isset($_SESSION['admin_username'])) {
    $_SESSION['admin_user_id'] = 1; // 设置默认ID
}

// 获取当前管理员信息
$admin = null;
if ($isLoggedInDb) {
    // 获取数据库连接
    require_once __DIR__ . '/DatabaseHelper.php';
    $db = Database::getInstance();
    
    // 获取用户信息
    $stmt = $db->query("SELECT * FROM " . DB_PREFIX . "users WHERE id = ? AND role = 'admin'", [$_SESSION['admin_user_id']]);
    $admin = $stmt->fetch();
    
    // 如果用户不存在或不是管理员，检查是否有简单登录
    if (!$admin && !$isLoggedInSimple) {
        unset($_SESSION['admin_user_id']);
        unset($_SESSION['admin_username']);
        header('Location: login.php');
        exit;
    }
}

// Check session timeout (30 minutes)
$timeout = 30 * 60; // 30 minutes in seconds
if (isset($_SESSION['admin_last_activity']) && (time() - $_SESSION['admin_last_activity'] > $timeout)) {
    // Last activity was more than 30 minutes ago
    session_unset();
    session_destroy();
    header('Location: login.php');
    exit;
}

// Update last activity time
$_SESSION['admin_last_activity'] = time();
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>KidsMind 管理系统</title>
    <!-- 本地CSS优先，CDN作为备选 -->
    <link rel="stylesheet" href="../css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <link rel="stylesheet" href="css/admin.css">
    <style>
        .sidebar {
            position: fixed;
            top: 0;
            bottom: 0;
            left: 0;
            z-index: 100;
            padding: 48px 0 0;
            box-shadow: inset -1px 0 0 rgba(0, 0, 0, .1);
            background-color: #343a40;
        }
        
        .sidebar-sticky {
            position: relative;
            top: 0;
            height: calc(100vh - 48px);
            padding-top: 0.5rem;
            overflow-x: hidden;
            overflow-y: auto;
        }
        
        .sidebar .nav-link {
            font-weight: 500;
            color: rgba(255, 255, 255, .75);
            padding: 0.75rem 1rem;
        }
        
        .sidebar .nav-link:hover {
            color: #fff;
        }
        
        .sidebar .nav-link.active {
            color: #fff;
            background-color: rgba(255, 255, 255, .1);
        }
        
        .sidebar .nav-link i {
            margin-right: 10px;
        }
        
        .navbar-brand {
            padding-top: 0.75rem;
            padding-bottom: 0.75rem;
            font-size: 1rem;
            background-color: rgba(0, 0, 0, .25);
            box-shadow: inset -1px 0 0 rgba(0, 0, 0, .25);
        }
        
        .navbar .navbar-toggler {
            top: 0.25rem;
            right: 1rem;
        }
        
        .navbar .form-control {
            padding: 0.75rem 1rem;
            border-width: 0;
            border-radius: 0;
        }
        
        .form-control-dark {
            color: #fff;
            background-color: rgba(255, 255, 255, .1);
            border-color: rgba(255, 255, 255, .1);
        }
        
        .form-control-dark:focus {
            border-color: transparent;
            box-shadow: 0 0 0 3px rgba(255, 255, 255, .25);
        }
        
        .main-content {
            padding-top: 1.5rem;
        }
        
        @media (max-width: 767.98px) {
            .sidebar {
                position: static;
                padding-top: 0;
                height: auto;
            }
            
            .sidebar-sticky {
                height: auto;
            }
            
            .main-content {
                padding-top: 0.5rem;
            }
        }
    </style>
</head>
<body>
    <nav class="navbar navbar-dark sticky-top bg-dark flex-md-nowrap p-0 shadow">
        <a class="navbar-brand col-md-3 col-lg-2 me-0 px-3" href="dashboard.php">
            <img src="../images/logo.png" alt="KidsMind" height="30" class="d-inline-block align-text-top me-2">
            KidsMind 管理系统
        </a>
        <button class="navbar-toggler position-absolute d-md-none collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#sidebarMenu" aria-controls="sidebarMenu" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>
        <div class="w-100"></div>
        <ul class="navbar-nav px-3 d-flex flex-row">
            <li class="nav-item text-nowrap me-3">
                <span class="nav-link">欢迎, <?php echo htmlspecialchars($_SESSION['admin_name']); ?></span>
            </li>
            <li class="nav-item text-nowrap">
                <a class="nav-link" href="logout.php"><i class="bi bi-box-arrow-right"></i> 退出</a>
            </li>
        </ul>
    </nav>
    
    <div class="container-fluid">
        <div class="row">
            <nav id="sidebarMenu" class="col-md-3 col-lg-2 d-md-block bg-dark sidebar collapse">
                <div class="sidebar-sticky pt-3">
                    <ul class="nav flex-column">
                        <li class="nav-item">
                            <a class="nav-link <?php echo $current_page == 'dashboard.php' ? 'active' : ''; ?>" href="dashboard.php">
                                <i class="bi bi-speedometer2"></i> 控制面板
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link <?php echo $current_page == 'modules.php' ? 'active' : ''; ?>" href="modules.php">
                                <i class="bi bi-grid-3x3-gap"></i> 认知模块管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link <?php echo $current_page == 'items.php' ? 'active' : ''; ?>" href="items.php">
                                <i class="bi bi-list-ul"></i> 模块内容管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link <?php echo $current_page == 'images.php' ? 'active' : ''; ?>" href="images.php">
                                <i class="bi bi-images"></i> 图片管理
                            </a>
                        </li>
                        <li class="nav-item mt-3">
                            <a class="nav-link" href="../index.html" target="_blank">
                                <i class="bi bi-eye"></i> 查看网站
                            </a>
                        </li>
                    </ul>
                </div>
            </nav>
            
            <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4 main-content">
                <?php if (isset($_SESSION['flash_message'])): ?>
                    <div class="alert alert-<?php echo $_SESSION['flash_type'] ?? 'info'; ?> alert-dismissible fade show">
                        <?php echo $_SESSION['flash_message']; ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                    <?php unset($_SESSION['flash_message'], $_SESSION['flash_type']); ?>
                <?php endif; ?> 